import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_viewmodel.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/edit_user_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';

import '../../../common_person_list_item_widget.dart';
import '../../../common_person_list_response.dart';
import 'add_member_commit_page.dart';
import 'change_member_page.dart';

///重复用户页面
class DuplicateUserPage extends StatefulWidget {
  static const String ROUTER = 'DuplicateUserPage';
  final String name;
  final List<CommonPersonBean> duplicateUserBeans;

  ///  部门班级信息
  final DepartmentOrClassListItemBean bean;

  DuplicateUserPage(this.name, this.duplicateUserBeans, this.bean);

  ///跳转方法
  static Future<bool> navigatorPush(
      BuildContext context,
      String name,
      List<CommonPersonBean> duplicateUserBeans,
      DepartmentOrClassListItemBean data) {
    return RouterUtils.routeForFutureResult<bool>(
      context,
      DuplicateUserPage(name, duplicateUserBeans, data),
      routeName: DuplicateUserPage.ROUTER,
    );
  }

  @override
  State<StatefulWidget> createState() {
    return DuplicateUserPageState();
  }
}

class DuplicateUserPageState extends BaseState<DuplicateUserPage> {
  TextEditingController nickInputController;

  @override
  void initState() {
    nickInputController = TextEditingController();
    super.initState();
    nickInputController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: Column(
        children: <Widget>[
          VgTopBarWidget(),
          Container(
              margin: EdgeInsets.symmetric(horizontal: 15),
              padding: EdgeInsets.all(15),
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  borderRadius: BorderRadius.all(Radius.circular(12))),
              height: 160,
              width: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '存在重名用户，需添加备注名予以区分',
                    style: TextStyle(
                        fontSize: 12,
                        color: ThemeRepository.getInstance()
                            .getMinorYellowColor_FFB714()),
                  ),
                  _nameAndNickWidget(),
                  _buttonWidget(),
                  // _
                ],
              )),
          Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 15, top: 15),
              child: Text(
                '或选择已有用户继续操作',
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance()
                        .getDefaultGrayColor_FF5E687C()),
              )),
          Expanded(
            child: _similarWidget(),
          ),
        ],
      ),
    );
  }

  ///姓名和昵称
  _nameAndNickWidget() {
    return Container(
      margin: EdgeInsets.only(top: 12, bottom: 16),
      height: 40,
      foregroundDecoration: BoxDecoration(
          shape: BoxShape.rectangle,
          border: Border.all(
              color: ThemeRepository.getInstance()
                  .getTextMinorGreyColor_808388()
                  .withOpacity(0.5),
              width: 1),
          borderRadius: BorderRadius.all(Radius.circular(4))),
      child: Row(
        children: <Widget>[
          Container(
            height: 40,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 18),
            decoration: BoxDecoration(
                shape: BoxShape.rectangle,
                color: ThemeRepository.getInstance().getLineColor_3A3F50(),
                border: Border.all(
                    color: ThemeRepository.getInstance()
                        .getTextMinorGreyColor_808388()
                        .withOpacity(0.5),
                    width: 1),
                borderRadius: BorderRadius.only(
                    topRight: Radius.zero,
                    topLeft: Radius.circular(4),
                    bottomRight: Radius.zero,
                    bottomLeft: Radius.circular(4))),
            child: Container(
              constraints: BoxConstraints.loose(Size(87.0, 40)),
              child: Text(
                widget.name,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 17,
                    fontWeight: FontWeight.bold,
                    color: ThemeRepository.getInstance()
                        .getTextMainColor_D0E0F7()),
              ),
            ),
          ),
          Expanded(
            child: CommonEditCallbackWidget(
              editingController: nickInputController,
              height: 40,
              hintText: "请输入备注名",
              fontSize: 14,
              showIcon: false,
            ),
          ),
        ],
      ),
    );
  }

  ///创建按钮
  Widget _buttonWidget() {
    return Container(
      width: double.infinity,
      height: 40,
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: nickInputController.text.length > 0,
        height: 40,
        radius: BorderRadius.all(Radius.circular(4)),
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 12,
        ),
        selectedTextStyle: TextStyle(color: Colors.white, fontSize: 12),
        text: "创建",
        textSize: 15,
        onTap: () async {
          //提交按钮
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
          if (nickInputController.text.length > 0) {
            bool result;
            if (widget.bean.isClass()) {
              result = await AddMemberFromSelectPage.navigatorPush(
                  context, widget.name,
                  nick: nickInputController.text,
                  classid: widget.bean?.getId(),
                  className: widget.bean?.getName(),type: "班级");
            }
            if (widget.bean.isDepartment()) {
              result = await AddMemberFromSelectPage.navigatorPush(
                  context, widget.name,
                  nick: nickInputController.text,
                  departmentId: widget.bean?.getId(),
                  department: widget.bean?.getName(),type: "部门");
            }
            if (result != null && result) {
              RouterUtils.pop(context, result: true);
            }
          }
        },
      ),
    );
  }

  _similarWidget() {
    return ListView.builder(
      padding: EdgeInsets.zero,
      itemBuilder: (context, index) {
        CommonPersonBean item = widget.duplicateUserBeans[index];
        return GestureDetector(
          onTap: () async {
            bool result;
            if (widget.bean.isClass()) {
              if (item.isStu()) {
                if (item.classname != null &&
                    item.classname.contains(widget.bean.getName())) {
                  CommonISeeDialog.navigatorPushDialog(context,
                      content: '该学员已在该班级下，无法继续操作');
                } else {
                  String strClassName = widget.bean?.getName();
                  String strClassIds = widget.bean?.getId();
                  if(item?.classname!=null && item?.classname!=""){
                    strClassName = strClassName +","+ item?.classname;
                    strClassIds = strClassIds +","+ item?.classid;
                  }
                  result = await ChangeMemberFromSelectPage.navigatorPush(
                      context, item.name, item.fuid, item.fid,
                      nick: nickInputController.text,
                      classid: strClassIds,
                      className: strClassName);
                }
              } else {
                CommonISeeDialog.navigatorPushDialog(context,
                    content: '无法将该员工添加至班级下');
              }
            }
            if (widget.bean.isDepartment()) {
              if (!item.isStu()) {
                String strDepartmentName = widget.bean?.getName();
                String strDepartmentIds = widget.bean?.getId();
                if(item?.department!=null && item?.department!=""){
                  strDepartmentName = strDepartmentName +","+ item?.department;
                  strDepartmentIds = strDepartmentName +","+ item?.departmentid;
                }
                if (item.department == null) {
                  result = await ChangeMemberFromSelectPage.navigatorPush(
                      context, item.name, item.fuid, item.fid,
                      nick: nickInputController.text,
                      departmentId: strDepartmentIds,
                      department: strDepartmentName);
                } else {
                  if (widget.bean.getName() == item.department) {
                    CommonISeeDialog.navigatorPushDialog(context,
                        content: '该用户已在该部门下，无法继续操作');
                  } else {
                    CommonISeeDialog.navigatorPushDialog(context,
                        content: '该员工已被添加至别的部门，如需调整部门，请联系超级管理员');
                  }
                }
              } else {
                CommonISeeDialog.navigatorPushDialog(context,
                    content: '无法将该学员添加至部门下');
              }
            }
            if (result != null && result) {
              RouterUtils.pop(context, result: true);
            }
          },
          child: Container(
            height: 60,
            color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
            child: CommonListItemWidget(
              putpicurl: item.putpicurl,
              napicurl: item.napicurl,
              name: item.name,
              nick: item.nick,
              phone: item.phone,
              department: item.department,
              projectname: item.projectname,
              classname: item.classname,
              city: item.city,
              isAlive: item.isAlive(),
              groupName: item.groupName,
              number: item.number,
              uname: item.uname,
              lastPunchTime: item.lastPunchTime,
              selectMode: true,
            ),
          ),
        );
      },
      itemCount: widget.duplicateUserBeans.length,
    );
  }
}
